import React from 'react';
import { Card, Row, Col, Space, Button, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import AddForm from './components/AddForm';
import { add } from '@/services/Admin';
import {history} from 'umi';

class Add extends React.Component {
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
    this.state = {isLoading: false};
  }

  /* 重置 */
  onReset = () => {
    const {resetFields} = this.formRef.current;
    resetFields();
  }

  /* 确认 */
  onConfirm = async () => {
    try {
      const {validateFields} = this.formRef.current;
      const values = await validateFields();
      const params = {...values};
      params.status = values.status ? 1 : 2;
      if (params.password !== params.confromPassword) throw new Error('确认密码不正确');
      this.setState({isLoading: true});
      await add({...params});
      message.success('新增成功！');
      setTimeout(function() {history.goBack()}, 1500)
    } catch (e) {
      !e.code && e.message ? message.warning(e.message) : null
    } finally {
      this.setState({isLoading: false});
    }
  }

  render() {
    const {onConfirm, onReset, id, formRef } = this;
    const isLoading = this.state.isLoading;
    return (
      <PageContainer>
        <Card
          title='添加内容'
          bodyStyle={{ paddingTop: 48, paddingBottom: 48 }}
          bordered={false}>
          <div style={{ width: '70vw' }}>
            <AddForm ref={formRef} />
            <Row>
              <Col span={6}></Col>
              <Col span={6}>
                <Space>
                  <Button onClick={() => {history.goBack()}}>取消</Button>
                  <Button onClick={onReset}>重置</Button>
                  <Button loading={isLoading} type="primary" onClick={onConfirm}>确定</Button>
                </Space>
              </Col>
            </Row>
          </div>
        </Card>
      </PageContainer>
    );
  }
}

export default Add;
